<?php
	class Database
	{
		protected $pdo;
		
		static function getDatabase()
		{
			return new Database(Application::getParameter('dbserver'),
										Application::getParameter('dbname'),
										Application::getParameter('dbuser'),
										Application::getParameter('dbpassword'));
			
		}
		
		function __construct($host, $db, $user, $password)
		{
			$this->pdo = new PDO("mysql:host=$host;dbname=$db", $user, $password);
			$this->pdo->query("SET NAMES 'utf8'");
		}
		public function lastInsertId()
		{
			return $this->pdo->lastInsertId();
		}
		public function query($sqlId, $params)
		{
			$sql = null;
			return $this->execute($sqlId, $params, $sql);
		}
		
		public function queryForColumn($sqlId, $params, $columnIndex, $defaultValue = null)
		{
			$sql = null;
			$ret = $this->execute($sqlId, $params, $sql);
			if ($ret === true)
				return $sql->fetchColumn($columnIndex);
			else 
				return $defaultValue;
		}
		
		public function queryForObject($sqlId, $params, $className = null, $defaultValue = null)
		{
			$sql = null;
			$ret = $this->execute($sqlId, $params, $sql);
			if ($ret === true)
			{
				if ($className != null)
					$sql->setFetchMode(PDO::FETCH_CLASS, $className);
				else
					$sql->setFetchMode(PDO::FETCH_OBJ);
					
				return $sql->fetch();
			}
			else 
				return $defaultValue;
		}
		
		public function queryForList($sqlId, $params, $className = null, $defaultValue = null)
		{
			$sql = null;
			$ret = $this->execute($sqlId, $params, $sql);
			if ($ret === true)
			{
				if ($className != null)
					$sql->setFetchMode(PDO::FETCH_CLASS, $className);
				else
					$sql->setFetchMode(PDO::FETCH_OBJ);
					
				return $sql->fetchAll();
			}
			else 
				return $defaultValue;
		}
		
		protected function execute($sqlId, $params, &$sql)
		{
			$sql = $this->parseSql($this->getSqlElement($sqlId), $params);
			if ($sql->execute())
			{
				return true;
			}
			else 
			{
				return $sql->errorInfo();
			}
			
		}
		
		protected function getSqlElement($sqlId)
		{
			$tmp = explode('.', $sqlId);
		//	$sqlFile = SITE_PATH. 'data' .DS.$tmp[0]. '.xml';
			$sqlFile = SITE_PATH.'models'.DS.$tmp[0].DS.$tmp[0].'.xml';
			$root = simplexml_load_file($sqlFile);
			foreach($root->sql as $sql)
			{
				if ($sql['Id'] == $tmp[1])
					return $sql;
			}
			return null;
		}
		
		protected function parseSql($sqlElement, $params)
		{
			$sql = $this->pdo->prepare((string)$sqlElement);
			
			if ($params != null & !is_array($params))
				$params = array($params);
				
			for ($i = 1; $i <= count($params); $i++)
			{
				$sql->bindValue($i, $params[$i-1]);
			}
			
			return $sql;		
		}
        
        
	}
?>